<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="充电站" prop="cs_name">
        <el-input
            v-model="queryParams.cs_name"
            placeholder="请输入充电站"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单时间" prop="date">
        <el-date-picker clearable
                        v-model="selectedMonth"
                        type="month"
                        value-format="YYYY-MM"
                        placeholder="请选择订单时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">

      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <div style="display:flex;flex-wrap: wrap;height: 400px;width: 1000px">
      <div style="display:flex;flex-direction: column;width: 200px;margin-left: 20px">
        <div class="a">
          <div>充电费：</div>
          <div style="margin-top: -14px">{{totalcdMoney}}</div>
        </div>
        <div class="a">
          <div>服务费：</div>
          <div style="margin-top: -14px">{{totalserviceMony}}</div>
        </div>
        <div class="a">
          <div>营收合计：</div>
          <div style="margin-top: -14px">{{totalyingshouMoney}}</div>
        </div>
      </div>
      <div style="width: 300px;height: 200px;margin-left: 100px"><e-charts class="chart" :option="option2" /></div>
      <div style="width: 250px;height: 200px;margin-left: 50px"><e-charts class="chart" :option="option3" /></div>
    </div>
    <el-table v-loading="loading" :data="listAll"  @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="日期" align="center"  width="180">
        <template #default="scope">
          <!-- 直接使用charging_date字段 -->
          <span v-if="scope">
              {{ scope.row.date }}
         </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="服务费" align="center" >
        <template #default="scope">
          {{ (scope.row.total_payment - scope.row.total_charging_kwh * 1.2).toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column label="充电费" align="center"  >
        <template #default="scope" prop="total_payment">
          <span>{{ (scope.row.total_charging_kwh * 1.2).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="营收合计" align="center" prop="total_payment" />
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

  </div>
</template>

<script setup name="Ysorder">
import { listYsorder, getYsorder, delYsorder, addYsorder, updateYsorder } from "@/api/system/ysorder"
import { getChartData,selecttotal } from "@/api/system/yunyingrecord"
import {ref} from "vue";
import dayjs from 'dayjs' // 引入 dayjs


const { proxy } = getCurrentInstance()

const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const listAll = ref([]);
const listst = ref([]);
const listChargeMoney = ref([]);
const listServiceMoney = ref([]);
const totalyingshouMoney = ref([])
const totalserviceMony = ref([])
const totalcdMoney = ref([])

const list = ref([])
const zhifufangshi = ref(["支付宝","微信"])
const selectedMonth = ref(getCurrentMonth()) // 使用这个替代 sselectedMonth
const all_wechat_count = ref([])
const all_alipay_count = ref([])

const tableDatas = reactive({
  tableData: [],
  daychongidanmoney: null,
  dayfuwumoney: null,

})

const payType = reactive({
  "微信支付次数": all_wechat_count,
  "支付宝次数": all_alipay_count,
})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    oNumber: null,
    oStationId: null,
    oAmount: null,
    oMoney: null,
    oHuiyuanId: null,
    oType: null,
    oStatus: null,
    oTime: [],
    csName: null,
    month: null,
    date: [],
    total_charging_kwh: 0,
    total_payment: 0,
    alipay_count: 0,
    wechat_count: 0,
    cs_name: null,

  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)
const option3 = ref({
  tooltip: {
    trigger: 'item'
  },
  legend: {
    top: '5%',
    left: 'center'
  },
  series: [{
    name: '支付方式',
    type: 'pie',
    radius: ['40%', '60%'],
    avoidLabelOverlap: false,
    itemStyle: {
      borderRadius: 10,
      borderColor: '#fff',
      borderWidth: 2
    },
    label: {
      show: false,
      position: 'center'
    },
    emphasis: {
      label: {
        show: true,
        fontSize: 18,
        fontWeight: 'bold'
      }
    },
    labelLine: {
      show: false
    },
    data: [{ value: all_wechat_count.value, name: '微信支付' },
      { value: all_alipay_count.value, name: '支付宝支付' }],}
  ]
})

const option2 = ref({
  title: {
    text: '8月营收总额'
  },
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['Email', 'Union Ads', 'Video Ads', 'Direct', 'Search Engine']
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  toolbox: {
    feature: {
      saveAsImage: {}
    }
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: listAll.value.map(item => item.date)
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '充电金额',
      type: 'line',
      data: listAll.value.map(item => item.total_payment)
    },
    {

      name: '服务费',
      type: 'line',
      data: listAll.value.map(item => (item.total_payment - item.total_charging_kwh * 1.2).toFixed(2))
    },

  ]
});
// function getweixinlis(){
//   selecttotal().then(response =>{
//     console.log(8888999777)
//     console.log(response)
//     payType.value = response.map(item => item.pay_count)
//
//   })
// }
onMounted(()=>{
  queryParams.value.month = getCurrentMonth(); // 初始化默认月份
  getList()
})
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.recordId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}
function getCurrentMonth() {
  const now = new Date();
  return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`;
}

// function getListall() {
//   getChartData().then(response => {
//     tableDatas.tableData = response.map(item => ({
//       ...item,
//       charging_date: item.charging_date || item.oTime || '', // 兼容不同字段名
//       daychongidanmoney: (item.total_charging_amount * 1.2).toFixed(2),
//       dayfuwumoney: (item.total_charging_money - item.total_charging_amount * 1.2).toFixed(2)
//     }));
//
//     console.log(response)
//     listAll.value = response
//     list.value = listAll.value.map(item => item.charging_date)
//     listChargeMoney.value = listAll.value.map(item => item.total_charging_money);
//     listServiceMoney.value = listAll.value.map(item => (item.total_charging_money - item.total_charging_amount * 1.2).toFixed(2));
//     totalyingshouMoney.value = listAll.value.reduce((sum, item) => sum + item.total_charging_money, 0).toFixed(2);
//     totalcdMoney.value = listAll.value.reduce((sum,item) =>((sum+ item.total_charging_amount * 1.2)),0).toFixed(2);
//     totalserviceMony.value = (totalyingshouMoney.value-totalcdMoney.value).toFixed(2);
//     console.log(listAll.value.map(item => item.total_charging_money))
//   })
// }

/** 查询营收分析列表 */
function getList() {
  loading.value = true
  queryParams.value.month = selectedMonth.value;
  listYsorder({
    month: selectedMonth.value,
    cs_name: queryParams.value.cs_name // 注意这里使用 cs_name 而不是 csName
  }).then(response => {

    total.value = response.total
    loading.value = false
    // recordList.value = response
    if (response && response.length > 0) {

      console.log(response)
      console.log(91111111)
      listAll.value = response
      //日期
      queryParams.value.date = listAll.value.map(item =>item.date)
      //冲带度数
      queryParams.value.total_charging_kwh = listAll.value.map(item =>item.total_charging_kwh)
      //支付总额
      queryParams.value.total_payment = listAll.value.map(item =>item.total_payment)
      console.log(queryParams.value.total_payment)

      //支付宝次数
      queryParams.value.alipay_count = listAll.value.map((sum, item) =>item.alipay_count)
      console.log( queryParams.value.alipay_count)
      //微信次数
      queryParams.value.wechat_count = listAll.value.map((sum, item) =>item.wechat_count)
      console.log(queryParams.value.wechat_count)
      all_wechat_count.value = listAll.value.reduce((sum,item) =>sum+item.wechat_count,0)
      all_alipay_count.value = listAll.value.reduce((sum,item) =>sum+item.alipay_count,0)

      totalyingshouMoney.value = listAll.value.reduce((sum, item) => sum + item.total_payment, 0).toFixed(2);
      totalcdMoney.value = listAll.value.reduce((sum,item) =>((sum+ (item.total_charging_kwh * 1.2))),0).toFixed(2);
      totalserviceMony.value = (totalyingshouMoney.value-totalcdMoney.value).toFixed(2);
      total.value = response.total
      loading.value = false
    } else {
      // 清空表格数据
      listAll.value = [];
      list.value = [];
      queryParams.value.csName = null;
      // 清空图表数据
      totalDate.value = [];
      totalData.value = [];
      totalRechargeAmount.value = [];
      totalRechargeTime.value = [];

      // 清空汇总数据
      listAll.value = response

      listChargeMoney.value = 0;
      listServiceMoney.value = 0;
      totalyingshouMoney.value = 0;
      totalcdMoney.value = 0;
      totalserviceMony.value = 0;

    }
    loading.value = false;
  }).catch(error => {
    console.error("获取数据失败:", error);
    loading.value = false;
    // 清空所有数据
    queryParams.value = [];
    listAll.value = [];
    list.value = [];
    // ...其他清空操作...

  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}
function formatDate(dateString) {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
}

// 表单重置
function reset() {
  form.value = {
    oId: null,
    oNumber: null,
    oStationId: null,
    oAmount: null,
    oMoney: null,
    oHuiyuanId: null,
    oType: null,
    oStatus: null,
    oTime: null
  }
  proxy.resetForm("ysorderRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  queryParams.value.month = selectedMonth.value // 确保月份参数被更新
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
// function handleSelectionChange(selection) {
//   ids.value = selection.map(item => item.oId)
//   single.value = selection.length != 1
//   multiple.value = !selection.length
// }

/** 新增按钮操作 */


</script>
<style>
.chart {

  height: 300px;
}
.a{
  margin-top: 20px;
  height: 80px;
  text-align: center;
  line-height: 50px;
  background: linear-gradient(to right, rgba(0, 0, 255, 0.5), rgba(0, 128, 255, 0.5));
}
</style>
